﻿using MESMian.Common;
using MESMian.Context;
using MESMian.Test;
using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MESMian.Forms.ProductionCategory
{
    public partial class ProductionCategoryAddEdit : AddEditBase
    {

        ProductCategories? editModel;
        public ProductionCategoryAddEdit(int editId) : base(editId)
        {
            InitializeComponent();
            this.editId = editId;
            Load += ProductionCategoryAddEdit_Load;
            btnSave.Click += BtnSave_Click;
        }

        private void ProductionCategoryAddEdit_Load(object? sender, EventArgs e)
        {
            if (editId > 0)
            {
                Text = "产品类型-编辑";
                using (var mtx = new MyContext())
                {
                    editModel = mtx.ProductCategories.Find(editId);
                    if (editModel != null)
                    {
                        txtProductCategory.Text = editModel.ProductCategoryName;
                    }
                }
            }
            else
            {
                Text = "产品类型-添加";
            }
        }



        private void BtnSave_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtProductCategory.Text))
            {
                MessageBox.Show("产品类型名称不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            using (var mtx = new MyContext())
            {

                if (editId > 0) { }
                else
                {
                    var query = mtx.ProductCategories.Where(item =>
    item.ProductCategoryName == txtProductCategory.Text);
                    if (query.Count() >= 1)
                    {
                        MessageBox.Show("设备类型名称重复！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    var model = new Model.ProductCategories()
                    {
                        ProductCategoryName = txtProductCategory.Text,
                        CreateUserId = LoginInfo.Id,
                    };
                    mtx.Entry(model).State = EntityState.Added;
                }
                mtx.SaveChanges();
                DialogResult = DialogResult.OK;
            }


        }


    }
}
